// !封装渲染页面的函数
async function render() {
  const res = await axios.get("/students");
  const htmlArr = res.data.map((item) => {
    return `
    <tr>
      <td>${item.name}</td>
      <td>${item.age}</td>
      <td>${item.gender === 0 ? "男" : "女"}</td>
      <td>${item.group}</td>
      <td>${item.hope_salary}</td>
      <td>${item.salary}</td>
      <td>${item.province}-${item.city}-${item.area}</td>
      <td>
        <a href="javascript:;" class="text-success mr-3"><i data-id=${
          item.id
        } class="bi bi-pen"></i></a>
        <a href="javascript:;" class="text-danger"><i data-id=${
          item.id
        } class="bi bi-trash"></i></a>
      </td>
    </tr>
    `;
  });
  document.querySelector(".list").innerHTML = htmlArr.join("");
  document.querySelector(".total").innerHTML = res.data.length;
}
render();

// !模态框
const modalBox = new bootstrap.Modal(document.querySelector("#modal"));

// !获取数据
const p = document.querySelector("[name=province]");
const c = document.querySelector("[name=city]");
const a = document.querySelector("[name=area]");
const form = document.querySelector("#form");

// ! 点击删除按钮和修改按钮,触发相应的功能(利用事件委托)
document.querySelector("tbody").addEventListener("click", async (e) => {
  // 拿到 id 值
  const id = e.target.dataset.id;
  // 先判断点了哪个按钮
  if (e.target.classList.contains("bi-trash")) {
    // 点了删除按钮，对应的功能
    try {
      const res = await axios.delete(`/students/${id}`);
      setTimeout(() => {
        alert("删除学生成功");
      }, 300);
      render();
    } catch (err) {
      console.log(err);
    }
  } else if (e.target.classList.contains("bi-pen")) {
    // 点了修改按钮，对应的功能
    document.querySelector(".modal-title").innerHTML = "修改学员";
    modalBox.id = id;
    modalBox.show();
    const res = await axios.get(`/students/${id}`);
    // console.log(res);
    for (const k in res.data) {
      const ipt = document.querySelector(`[name=${k}]`);
      if (ipt !== "gender") {
        ipt !== null && (ipt.value = res.data[k]);
      } else {
        const genders = document.querySelectorAll("[name=gender]");
        genders[res.data[gender]].checked = true;
      }
    }
    // 处理市 区
    await renderProvince(res.data.province);
    await renderCity(res.data.city);
    await renderArea(res.data.area);
  }
});

// ! 添加按钮的功能
document.querySelector("#openModal").addEventListener("click", () => {
  document.querySelector(".modal-title").innerHTML = "添加学员";
  modalBox.id = "add";
  modalBox.show();
});

// ! 模态框确认按钮的功能
document.querySelector("#submit").addEventListener("click", async () => {
  // 获取数据
  const data = serialize(form, { hash: true });
  // 处理数据(用for in 遍历出来，然后将可以转换为 number 类型的转化)
  for (const k in data) {
    if (isNaN(data[k]) === false) {
      data[k] = +data[k];
    }
  }
  // 判断了是什么功能里面的确认按钮
  if (modalBox.id === "add") {
    // 添加时模态框的确认的功能
    try {
      const res = await axios.post("/students", data);
      setTimeout(() => {
        alert(res.message);
      }, 300);
    } catch (err) {
      console.log(err);
    }
  } else {
    const id = modalBox.id;
    try {
      const res = await axios.put(`/students/${id}`, data);
      setTimeout(() => {
        alert(res.message);
      }, 300);
    } catch (err) {
      console.log(err);
    }
  }
  modalBox.hide();
  render();
});


// !获取省数据
async function renderProvince(province = "") {
  const pRes = await axios.get("/api/province");
  const pArr = pRes.data.map((item) => {
    return `<option value="${item}">${item}</option>`;
  });
  p.innerHTML = pArr.join("");
  // 逻辑中断
  province !== "" && (p.value = province);
}
// !获取市数据
async function renderCity(city = "") {
  const cRes = await axios.get("/api/city", { params: { pname: p.value } });
  const cArr = cRes.data.map((item) => {
    return `<option value="${item}">${item}</option>`;
  });
  c.innerHTML = cArr.join("");
  // 逻辑中断
  city !== "" && (c.value = city);
}
// !获取区数据
async function renderArea(area = "") {
  const aRes = await axios.get("/api/area", {
    params: { pname: p.value, cname: c.value },
  });
  const aArr = aRes.data.map((item) => {
    return `<option value="${item}">${item}</option>`;
  });
  a.innerHTML = aArr.join("");
  // 逻辑中断
  area !== "" && (a.value = area);
}
// 省市区
async function renderSelect() {
  await renderProvince();
  await renderCity();
  await renderArea();
}
renderSelect();

// ! 省市联动
p.addEventListener("change", async () => {
  await renderCity();
  await renderArea();
});

// !市区联动
c.addEventListener("change", async () => {
  await renderArea();
});
